import { Model, DataTypes } from 'sequelize';
import sequelize from '@/config/database';
import User from './user.model';
import Post from './post.model';

// 定义用户岗位关联属性接口
interface UserPostAttributes {
  userId: number;
  postId: number;
}

// 用户岗位关联模型类
class UserPost extends Model<UserPostAttributes> implements UserPostAttributes {
  public userId!: number;
  public postId!: number;
}

UserPost.init(
  {
    userId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'user_id',
      references: {
        model: User,
        key: 'user_id'
      }
    },
    postId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'post_id',
      references: {
        model: Post,
        key: 'post_id'
      }
    }
  },
  {
    sequelize,
    tableName: 'sys_user_post',
    timestamps: false
  }
);

// 建立关联关系
User.belongsToMany(Post, {
  through: UserPost,
  foreignKey: 'userId',
  otherKey: 'postId',
  as: 'posts'
});

Post.belongsToMany(User, {
  through: UserPost,
  foreignKey: 'postId',
  otherKey: 'userId',
  as: 'users'
});

// 为UserPost添加Post关联以便在查询时使用
UserPost.belongsTo(Post, {
  foreignKey: 'postId',
  as: 'Post'
});

// 为UserPost添加User关联
UserPost.belongsTo(User, {
  foreignKey: 'userId',
  as: 'User'
});

export default UserPost; 